package org.crepi22.finecrop;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

class Clip extends Thread {
    int sX, sY, eX, eY;
    final Continuation continuation;
    Photo photo;
    
    Clip(Continuation continuation,Photo photo, float sX, float sY, float eX, float eY) {
        this.continuation = continuation;
        this.photo = photo;
        this.sX = (int) sX;
        this.sY = (int) sY;
        this.eX = (int) eX;
        this.eY = (int) eY;
    }

    public void run() {
        try {
            File clippedImageFile = File.createTempFile("clipped", ".jpg"); //$NON-NLS-1$ //$NON-NLS-2$
            
            String[] command = new String[] {
                Config.getConvertPath(),
                "-crop", //$NON-NLS-1$
                photo.formatBounds(sX,sY,eX,eY),
                photo.getPath(),
                clippedImageFile.getAbsolutePath()
            };
            synchronized(continuation) {
                continuation.showEffect(true);
                Process p = Runtime.getRuntime().exec(command);
                int exit = p.waitFor();
                if (exit == 0) {
                    continuation.runFile(clippedImageFile);
                } else {
                    continuation.error(String.format (Messages.getString("Clip.bad_result"), exit, Arrays.toString(command))); //$NON-NLS-1$
                }
            }
        } catch (IOException e) {
            continuation.error(e.getMessage());
        } catch (InterruptedException e) {
            continuation.error(e.getMessage());
        } finally {
            continuation.showEffect(false);
        }
    }

}

